import os
import time
import random
import pandas as pd
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import jieba
from wordcloud import WordCloud
import matplotlib.pyplot as plt
from collections import Counter
import re

# 3. 访问歌曲页面并获取评论
def get_comments(song_id="2083785152", max_pages=10):
    comments = []
   
    driver.get(' https://music.163.com/')
    time.sleep(random.uniform(1, 3))
    driver.get(f'https://music.163.com/song?id={song_id}')
    driver.refresh()
    # 等待页面加载并切换到评论iframe
    try:
        print("等待页面加载并切换到评论iframe")
        WebDriverWait(driver, 10).until(
            EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR, "iframe[id^='g_iframe']"))
        )
    except:
        print("无法切换到评论iframe")
        return comments
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    print("滑动窗口完成")
    print("获取初始评论")
    # 获取初始评论
    comments = get_page_comments(driver)
    print("获取初始评论完成")
    
    a_element = driver.find_element_by_class_name("u-page")
    aa = a_element.find_elements(By.TAG_NAME, "a")
    
    # 翻页获取更多评论
    for page in range(1, max_pages):
        try:
            for a in aa:
                if(a.text == str(page)):
                    a.click()
                    break            
            time.sleep(random.uniform(1, 3))  # 随机等待1-3秒
            
            # 获取当前页评论
            page_comments = get_page_comments(driver)
            comments.extend(page_comments)
            
            print(f'已获取第 {page+1} 页评论，共 {len(comments)} 条')
        except Exception as e:
            print(f'翻页失败: {e}')
            break
    
    return comments

def get_page_comments(driver):
    page_comments = []
    WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CLASS_NAME, "itm")))
    try:
#         获取评论条目
        elements = driver.find_elements_by_class_name("itm")
        for element in elements:
            try:
                user=element.find_element(By.CLASS_NAME, "s-fc7").text
                content = element.find_element(By.CLASS_NAME, "f-brk").text.split("：")[1]
                likes = element.find_element(By.XPATH, './/a[@data-type="like"]').text
                match = re.search(r'\((.*?)\)', likes)
                if match:
                    number_text = match.group(1)
                    if "万" in number_text:
                        number = float(number_text.replace("万", "")) * 10000
                    else:
                        number = float(number_text) if number_text else 0
                else:
                    number = 0
                page_comments.append({
                                'user': user,
                                'content': content,
                                'likes': int(number)
                            })
            except Exception as e:
                print(f'解析单条评论失败: {e}')
                continue
    except Exception as e:
        print(f'获取页面评论失败: {e}')

    return page_comments
# === 第三步：数据存储 ===
def save_to_excel(comments, filename='comments.xlsx'):
    df = pd.DataFrame(comments, columns=['评论内容'])
    df.to_excel(filename, index=False)
# === 第四步：文本分析 ===
def analyze_comments(comments, stopwords_path='stopwords.txt'):
    # 加载停用词
    with open(stopwords_path, 'r', encoding='utf-8') as f:
        stopwords = set([line.strip() for line in f])
 
    # 合并所有评论
    all_text = ' '.join(comments)
    
    # 使用结巴分词
    words = jieba.cut(all_text)
    filtered_words = [word for word in words 
                     if len(word) > 1 
                     and word not in stopwords
                     and not word.isdigit()]
 
    # 统计词频
    word_counts = pd.Series(filtered_words).value_counts()
    return word_counts
 
# === 第五步：词云可视化 ===
def generate_wordcloud(word_counts, output_path='wordcloud.png'):
    wc = WordCloud(
        font_path='simhei.ttf',  # 中文字体路径
        background_color='white',
        max_words=200,
        width=800,
        height=600
    )
    
    wc.generate_from_frequencies(word_counts)
    plt.imshow(wc, interpolation='bilinear')
    plt.axis('off')
    plt.savefig(output_path, dpi=300, bbox_inches='tight')
 


if __name__ == '__main__':
	song_id = "2083785152"
	driver = webdriver.Chrome()
	# 获取评论
	comments = get_comments(song_id, max_pages=20)
	# 保存数据
	save_to_excel(comments)
	print(f'共爬取 {len(comments)} 条评论')
		# 关闭浏览器
	driver.close()
	# 提取content数据为数组
	content_array = [item['content'] for item in comments]
	# 文本分析
	word_counts = analyze_comments(content_array)
	print('高频词汇TOP20：')
	print(word_counts.head(20))
	# 生成词云
	generate_wordcloud(word_counts)
	print('词云已生成：wordcloud.png')
